package com.sky.interceptor;

import com.sky.constant.JwtClaimsConstant;
import com.sky.context.BaseContext;
import com.sky.properties.JwtProperties;
import com.sky.utils.JwtUtil;
import io.jsonwebtoken.Claims;
import lombok.extern.slf4j.Slf4j;
import org.apache.poi.util.StringUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@Slf4j
@Component
public class AdminLoginTokenInterceptor implements HandlerInterceptor {

    @Autowired
    private JwtProperties jwtProperties;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        log.info("拦截到了请求 {}", request.getRequestURI().toString());

        //1.获取请求头中令牌
        String jwt = request.getHeader(jwtProperties.getAdminTokenName());

        //2.校验令牌是否存在，不存在返回401
        if(!StringUtils.hasLength(jwt)){
            log.info("令牌为空, 返回401状态码");
            response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
            return false;
        }

        //3.判断令牌是否合法，不合法返回401
        try {
            Claims claims = JwtUtil.parseJWT(jwtProperties.getAdminSecretKey(), jwt);
            log.info("校验令牌, {}", claims);
            //获取员工id
            Long empId = Long.valueOf(claims.get(JwtClaimsConstant.EMP_ID).toString());
            //存员工id
            BaseContext.setCurrentId(empId);
        } catch (Exception e) {
            e.printStackTrace();
            log.info("令牌解析失败, 返回401状态码");
            response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
            return false;
        }

        //4.放行
        return true;

    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
        BaseContext.removeCurrentId();
    }

}
